package org.wisdom.ac.service;

import java.util.*;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.wisdom.ac.apis.ResourceController;
import org.wisdom.ac.dto.ResourceDto;
import org.wisdom.service.AppFacadeInfo;
import org.wisdom.service.WisdomRegistry;
import org.wisdom.vo.ResponseResult;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 启动类
 *
 * @author 张智研
 * @date 2022/06/14 20:55
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class AcApiRunner implements ApplicationRunner {
    private final Environment env;
    private final ResourceController resourceController;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        Map<String, List<AppFacadeInfo>> appFacadeMap = new HashMap<>(1);

        WisdomRegistry.APP_INFOS.iterator().forEachRemaining(appFacadeInfo -> {
            String appName = appFacadeInfo.getName();
            if (appName == null) {
                appName = env.getProperty("spring.application.name", "default");
            }
            appFacadeMap.computeIfAbsent(appName, k -> new ArrayList<>());
            appFacadeMap.get(appName).add(appFacadeInfo);
        });
        // 注册服务到鉴权中心
        appFacadeMap.keySet().iterator().forEachRemaining(appName -> {
            ResourceDto appDto = new ResourceDto();
            appDto.setId(appName);
            appDto.setTitle(appName);
            appDto.setPermission(appName);
            appDto.setCode(appName);
            appDto.setOutside(false);
            appDto.setHidden(false);
            appDto.setStatus(true);
            appDto.setTimeStamp(System.currentTimeMillis());
            log.info("注册应用[{}]到鉴权中心", appName);
            ResponseResult<String> result = resourceController.saveApp(appDto);
            if (result.getCode() == 0) {
                log.info("注册成功！");
            } else {
                log.error("注册失败！{}", result.getMsg());
            }
            appFacadeMap.get(appName).forEach(appFacadeInfo -> {
                Set<String> a;
                if (appFacadeInfo.getRequestMappingInfo().getPathPatternsCondition() != null) {
                    a = appFacadeInfo.getRequestMappingInfo().getPathPatternsCondition().getDirectPaths();
                    if (a.isEmpty()) {
                        a = appFacadeInfo.getRequestMappingInfo().getPathPatternsCondition().getPatternValues();
                    }
                    if (a.iterator().hasNext()) {
                        String url = a.iterator().next();
                        String methodType = appFacadeInfo.getRequestMappingInfo().getMethodsCondition().getMethods()
                            .iterator().next().name();
                        ResourceDto resourceDto = new ResourceDto();
                        String code = appName + "#" + methodType + url.replace(" ", "").replace("/", "#");
                        resourceDto.setId(code);
                        resourceDto.setRequestType(methodType);
                        resourceDto.setRequestUrl(url);
                        resourceDto.setAppId(appName);
                        resourceDto.setCode(code);
                        resourceDto.setStatus(true);
                        resourceDto.setTitle(appFacadeInfo.getTitle() != null ? appFacadeInfo.getTitle() : url);
                        resourceDto.setPermission(appFacadeInfo.getPermission());
                        resourceDto.setOutside(false);
                        resourceDto.setHidden(false);
                        resourceDto.setTimeStamp(System.currentTimeMillis());
                        log.info("注册服务[{} {}]到鉴权中心", methodType, url);
                        ResponseResult<String> result1 = resourceController.saveAppFacade(resourceDto);
                        if (result1.getCode() == 0) {
                            log.info("注册成功！");
                        } else {
                            log.error("注册失败！{}", result1.getMsg());
                        }
                    }
                }
            });
        });
    }
}
